package org.deadline.model.baseapp;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.deadline.model.config.EnumerationDataOnDemand;
import org.deadline.repository.baseapp.AddressRepository;
import org.deadline.service.baseapp.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;

@Component
@Configurable
public class AddressDataOnDemand {

	private Random rnd = new SecureRandom();

	private List<Address> data;

	@Autowired
    private PrincipalDataOnDemand principalDataOnDemand;

	@Autowired
    private EnumerationDataOnDemand enumerationDataOnDemand;

	@Autowired
    AddressService addressService;

	@Autowired
    AddressRepository addressRepository;

	public Address getNewTransientAddress(int index) {
        Address obj = new Address();
        setAddressLine1(obj, index);
        setAddressLine2(obj, index);        
        setCity(obj, index);
        setCountry(obj, index);
        setCountryCode(obj, index);
        setCreationDate(obj, index);
        setDeleted(obj, index);
        setModificationDate(obj, index);
        setPostalCode(obj, index);
        setStateCode(obj, index);
        setTerritoryCode(obj, index);
        return obj;
    }

	public void setAddressLine1(Address obj, int index) {
        String addressLine1 = "addressLine1_" + index;
        if (addressLine1.length() > 64) {
            addressLine1 = addressLine1.substring(0, 64);
        }
        obj.setAddressLine1(addressLine1);
    }

	public void setAddressLine2(Address obj, int index) {
        String addressLine2 = "addressLine2_" + index;
        if (addressLine2.length() > 64) {
            addressLine2 = addressLine2.substring(0, 64);
        }
        obj.setAddressLine2(addressLine2);
    }

	public void setCity(Address obj, int index) {
        String city = "city_" + index;
        if (city.length() > 100) {
            city = city.substring(0, 100);
        }
        obj.setCity(city);
    }

	public void setCountry(Address obj, int index) {
        String country = "country_" + index;
        if (country.length() > 64) {
            country = country.substring(0, 64);
        }
        obj.setCountry(country);
    }

	public void setCountryCode(Address obj, int index) {
        String countryCode = "c_" + index;
        if (countryCode.length() > 3) {
            countryCode = countryCode.substring(0, 3);
        }
        obj.setCountryCode(countryCode);
    }

	public void setCreationDate(Address obj, int index) {
        Date creationDate = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE), Calendar.getInstance().get(Calendar.SECOND) + new Double(Math.random() * 1000).intValue()).getTime();
        obj.setCreationDate(creationDate);
    }

	public void setDeleted(Address obj, int index) {
        Boolean deleted = true;
        obj.setDeleted(deleted);
    }

	public void setModificationDate(Address obj, int index) {
        Date modificationDate = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE), Calendar.getInstance().get(Calendar.SECOND) + new Double(Math.random() * 1000).intValue()).getTime();
        obj.setModificationDate(modificationDate);
    }

	public void setPostalCode(Address obj, int index) {
        String postalCode = "postalCode_" + index;
        if (postalCode.length() > 20) {
            postalCode = postalCode.substring(0, 20);
        }
        obj.setPostalCode(postalCode);
    }

	public void setStateCode(Address obj, int index) {
        String stateCode = "stateCode_" + index;
        if (stateCode.length() > 32) {
            stateCode = stateCode.substring(0, 32);
        }
        obj.setStateCode(stateCode);
    }

	public void setTerritoryCode(Address obj, int index) {
        String territoryCode = "territoryCode_" + index;
        if (territoryCode.length() > 32) {
            territoryCode = territoryCode.substring(0, 32);
        }
        obj.setTerritoryCode(territoryCode);
    }

	public Address getSpecificAddress(int index) {
        init();
        if (index < 0) {
            index = 0;
        }
        if (index > (data.size() - 1)) {
            index = data.size() - 1;
        }
        Address obj = data.get(index);
        Long id = obj.getId();
        return addressService.findAddress(id);
    }

	public Address getRandomAddress() {
        init();
        Address obj = data.get(rnd.nextInt(data.size()));
        Long id = obj.getId();
        return addressService.findAddress(id);
    }

	public boolean modifyAddress(Address obj) {
        return false;
    }

	public void init() {
        int from = 0;
        int to = 10;
        data = addressService.findAddressEntries(from, to);
        if (data == null) {
            throw new IllegalStateException("Find entries implementation for 'Address' illegally returned null");
        }
        if (!data.isEmpty()) {
            return;
        }
        
        data = new ArrayList<Address>();
        for (int i = 0; i < 10; i++) {
            Address obj = getNewTransientAddress(i);
            try {
                addressService.saveAddress(obj);
            } catch (ConstraintViolationException e) {
                StringBuilder msg = new StringBuilder();
                for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator(); iter.hasNext();) {
                    ConstraintViolation<?> cv = iter.next();
                    msg.append("[").append(cv.getConstraintDescriptor()).append(":").append(cv.getMessage()).append("=").append(cv.getInvalidValue()).append("]");
                }
                throw new RuntimeException(msg.toString(), e);
            }
            addressRepository.flush();
            data.add(obj);
        }
    }
}
